var conn = {};
let that = this;
let isfirst = true;
// console.log(getconfig())
WebIM.config = getconfig();
// WebIM.config = config;
conn = WebIM.conn = new WebIM.default.connection({
    appKey: WebIM.config.appkey,
    isHttpDNS: WebIM.config.isHttpDNS,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    apiUrl: WebIM.config.apiURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    heartBeatWait: WebIM.config.heartBeatWait,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval,
    isStropheLog: WebIM.config.isStropheLog,
    delivery: WebIM.config.delivery
})
conn.listen({ 
    onOpened: function (message) { //连接成功回调 
        console.log('成功登录')
        console.log(conn.isOpened())
        if(conn.isOpened()){//ture为登录，undifined为未登录；
			switch(isfirst){
				case 0:
					//账号密码登录
					vant.Toast.success('登陆成功')
					// return
					setTimeout(()=>{
						// window.location.href ='../pages/chatlist.html'
						location.href="/Welcome/chatlist";
					},3000)
				break;
				case 1:
					//聊天列表登录，chatlist
					// webvue.getFriends();
					// webvue.getGroups()
				break;
				case 2:
					//通讯录页面登录，addressbook
					webvue.getFriends();
				break;
				case 3:
					//对话页面登录，chatpage
				break;
				case 4:
					//群组列表页面登录，groupbook
					webvue.getGroups()
				break;
				case 5:
					//添加好友页面登录，addfriend
				break;
				case 6:
					//好友申请页面登录，newfriendask
				break;
				case 7:
					//"我"页面登录，me
				break;
				case 8:
					//发起群聊页面登录，creategroup
					webvue.getFriends()
				break;
				case 9:
					//群组详情页面登录，groupSet
					webvue.getmember()
				break;
				case 10:
					//好友详情页面登录，friendSet
					// webvue.getmember()
				break;
			}
        }
    },
    onClosed: function (message) { 
		console.log('>>>已关闭',message)
		setTimeout(()=>{
			window.location.href ='../pages/login.html'
		},1000)
	},         //连接关闭回调
    onTextMessage: function (message) {//收到文本消息
        console.log("收到文本消息", message);
		if(message.type == 'groupchat'){
			//群聊
			
		}
		if(isfirst == 1){
			//聊天列表 
			var namearr = [];
			var name;
			var sendID;
			var friendshowList =  getfriendshowList();
			if(message.type == 'chat'){
				sendID = message.from;
				name = message.from;
			}else if(message.type == 'groupchat'){
				sendID = message.to;
				name = message.ext.groupname;
			}
			if(message.contentsType == 'TEXT'){
				var lastmsg = message.data;
			}else if(message.contentsType == 'IMAGE'){
				var lastmsg = '[图片]';
			}
			var obj = {
				sendID:sendID,
				name:name,
				lastmsg:lastmsg,
				time:'2020-06-15',
				ishidden:false, 
				type:message.type,
				noreadnum:1
			}
			console.log('这是obj')
			console.log(obj)
			console.log(friendshowList)
			if(friendshowList.length>0){
				friendshowList.forEach((item,index)=>{
					namearr.push(item.name)
				})
				if(namearr.indexOf(name) == -1){
					console.log('indexOf是-1')
					pushfriendshowList(obj)
				}else{
					console.log(name)
					friendshowList.forEach((item,index)=>{
						console.log(item)
						if(item.name == name){
							item.ishidden = false;
							item.noreadnum =parseInt(item.noreadnum)+1;
							item.lastmsg = message.data;
						}
					})
				}
			}else{
				pushfriendshowList(obj)
				console.log(getfriendshowList())
			}

		}else if(isfirst == 3){
			//对话页面
			if(message.ext.other == 'videocall'){
				console.log('videocallvideocallvideocallvideocall')
				console.log(message.ext.confrId)
				console.log(message.ext.password)
				webvue.videochatting = true;
				var msgData = {
					self:'other',
					type:msgtype().TEXT,
					value:message.data,
					from:message.from,
					to:message.to,
					isvideo:true,
				}
				webvue.confrId = message.ext.confrId;
				webvue.password = message.ext.password;
				console.log(webvue.confrId)
				console.log(webvue.password)
			}else if(message.ext.other == 'websocmes'){
				var msgData = {
					self:'websocmes',
					type:msgtype().TEXT,
					value:message.data,
					from:message.from,
					to:message.to,
					websocmes:true,
				}
				// if(message.data.indexOf('退出视频')){
				// 	webvue.videochatting = false;
				// }
			}else if(message.ext.other == 'issharescream'){
				var msgData = {
					self:'other',
					type:msgtype().TEXT,
					value:message.data,
					from:message.from,
					to:message.to,
					issharescream:true,
				}
				webvue.sharing = true;
				webvue.confrId = message.ext.confrId;
				webvue.password = message.ext.password;
			}else{
				var msgData = {
					self:'main',
					type:msgtype().TEXT,
					value:message.data,
					from:message.from,
					to:message.to,
					videocall:false
				}
			}
			// let msgData = {
			// 	self:'main',
			// 	type:msgtype().TEXT,
			// 	value:message.data,
			// 	from:message.from,
			// 	to:message.to,
			// }
			pushDialog(getMsgData(msgData,msgtype().TEXT))
			webvue.scrolllistbox()
			console.log(getDialog())
		}
		addallnoreadnum()
    },    
    onEmojiMessage: function (message) { },   //收到表情消息
    onPictureMessage: function (message) { //收到图片消息
		console.log('收到图片消息')
		console.log(message)
		if(isfirst == 1){
			//聊天列表
			var namearr = [];
			var name;
			var sendID;
			var friendshowList =  getfriendshowList();
			if(message.type == 'chat'){
				sendID = message.from;
				name = message.from;
			}else if(message.type == 'groupchat'){
				sendID = message.to;
				name = message.ext.groupname;
			}
			var obj = {
				sendID:sendID,
				name:name,
				lastmsg:'[图片]',
				time:'2020-06-15',
				ishidden:false,
				type:message.type,
				noreadnum:1
			}
			console.log('这是obj')
			console.log(obj)
			if(friendshowList.length>0){
				friendshowList.forEach((item,index)=>{
					namearr.push(item.name)
				})
				if(namearr.indexOf(name) == -1){
					console.log('indexOf是-1')
					pushfriendshowList(obj)
				}else{
					console.log(name)
					friendshowList.forEach((item,index)=>{
						console.log(item)
						if(item.name == name){
							item.ishidden = false;
							item.noreadnum =parseInt(item.noreadnum)+1;
							item.lastmsg = '[图片]';
						}
					})
				}
			}else{
				pushfriendshowList(obj)
				console.log(getfriendshowList())
			}
		}else if(isfirst == 3){
			//对话页面
			let msgData = {
				self:'main',
				type:msgtype().IMAGE,
				value:message.url,
				valuearr:[message.url],
				from:message.from,
				to:message.to
			}
			pushDialog(msgData)
			webvue.scrolllistbox()
		}
		addallnoreadnum()
	}, 
    onCmdMessage: function (message) { },     //收到命令消息
    onAudioMessage: function (message) {
		console.log('收到音频消息')
		console.log(message)
	},   //收到音频消息
    onLocationMessage: function (message) { },//收到位置消息
    onFileMessage: function (message) { //收到文件消息
		console.log('收到文件消息')
		console.log(message)
	},    
	onCustomMessage: function ( message ) {
		//收到自定义消息
		console.log('>>>自定义消息',message)
		//语音：audio
		var type = message.customExts.type;
		var url = message.customExts.url;
		let msgData = {
			self:'main',
			type:msgtype().AUDIO,
			value:url,
			from:message.from,
			to:message.to
		}
		pushDialog(msgData)
		webvue.scrolllistbox()
	},  
    onVideoMessage: function (message) {
        var node = document.getElementById('privateVideo');
        var option = {
            url: message.url,
            headers: {
                'Accept': 'audio/mp4'
            },
            onFileDownloadComplete: function (response) {
                var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
                node.src = objectURL;
            },
            onFileDownloadError: function () { 
                console.log('File down load error.')
            }
        };
        WebIM.utils.download.call(conn, option);
    },   //收到视频消息
    onPresence: function (message) { //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
        console.log('好友请求',message)
		if(message.type === 'subscribe'){
			//别人申请你为好友
			var namearr = [];
			var friendAskListStor = getStorage('friendAskList');
			if(friendAskListStor.length>0){
				friendAskListStor.forEach((item,index)=>{
					namearr.push(item.from)
				})
				if(namearr.indexOf(message.from) != -1){
					friendAskListStor.forEach((item,index)=>{
						if(item.from == message.from){
							friendAskListStor.splice(index,1);
							friendAskList.splice(index,1);
							console.log(friendAskListStor)
							// saveStorage('friendAskList',friendAskLisst)
						}
					})
				}
			}
			setTimeout(()=>{
				message.isadd = false;
				addnewfriendnum()  
				pushFriendAskList(message)
				console.log(getFriendAskList())
			},800)
		}else if(message.type === 'subscribed'){
			//别人同意你的好友申请
			// webvue.friendasklist.forEach((item,index)=>{
			// 	if(item.from == message.from){
			// 		item.isadd = true;
			// 	}
			// })
			// vant.Toast(message.from+'同意你的好友申请啦！')
			
		}
    },      
    onRoster: function (message) {//处理好友申请
		console.log('处理好友申请',message)
	},         
    onInviteMessage: function (message) { },  //处理群组邀请
    onOnline: function () { },                  //本机网络连接成功
    onOffline: function () { },                 //本机网络掉线
    onError: function (message) { 
		console.log(message)
		if(message.type == 1){
			//账号密码错误
			vant.Toast('用户名或密码错误');
		}else if(message.type == 28){
			return
			//重新登录
			window.location.href ='../pages/login_reg.html'
			vant.Toast('请重新登录');
		}
	},          //失败回调
    onBlacklistUpdate: function (list) {       //黑名单变动
        // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
        console.log(list);
    },
    onRecallMessage: function (message) { },      //收到撤回消息回调
    onReceivedMessage: function (message) {
        console.log('消息发送到服务器');
    },    //收到消息送达服务器回执
    onDeliveredMessage: function (message) {
        console.log('消息发送到客户端');
    },   //收到消息送达客户端回执
    onReadMessage: function (message) { },        //收到消息已读回执
    onCreateGroup: function (message) { },        //创建群组成功回执（需调用createGroupNew）
    onMutedMessage: function (message) { }        //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
});